<template>
	<view class="login">
		<view :style="{
			padding: `${bottom}px 30px`,
		}">
			<!-- <up-image src="/static/logo.png"  mode="heightFix" width="128rpx" height="128rpx"></up-image> -->
			<view class="f-s-16 f-w-b u-m-t-24">欢迎登录德宝乒乓球</view>
			<view class="form-box">
				<u--form :model="loginForm" ref="uForm" errorType="toast" :labelWidth="0">
					<u-form-item prop="phone">
						<u--input prefixIconStyle="font-size: 24px;margin-left: 10px;"
							placeholder="手机号码" type="number" :maxlength="11" v-model="loginForm.phone" :customStyle="{
			                        borderBottom: '1px solid #E4E4E4',
			                        padding: '24rpx 12rpx',
			                        borderRadius: '12px',
			                        fontSize: '28rpx'
			                    }">
							<template #prefix>
								<view class="iconfont f-s-18 u-m-l-12">&#xe618;</view>
							</template>
						</u--input>
					</u-form-item>
					<u-form-item prop="code">
						<u-input type="number" :maxlength="6" prefixIconStyle="font-size: 24px;margin-left: 10px;"
							v-model="loginForm.code" placeholder="短信验证码" :customStyle="{
			                            borderBottom: '1px solid #E4E4E4',
			                            padding: '24rpx 12rpx',
			                            borderRadius: '12px',
			                            fontSize: '28rpx',
			                        }">
							<template #prefix>
								<view class="iconfont f-s-18 u-m-l-12">&#xe624;</view>
							</template>
							<template #suffix>
								<view class="code_style" v-if="isSend && loginForm.phone.length==11"
									@click="sendPhoneCode">获取验证码</view>
								<view class="code_style" v-if="!isSend">{{sendMsg}}</view>
							</template>
						</u-input>
					</u-form-item>
					<u-form-item>
						<view class="u-flex u-flex-items-center">
							<u-checkbox-group v-model="agree">
								<u-checkbox shape="circle" activeColor="#2080F7" :size="16" name="agree">
								</u-checkbox>
							</u-checkbox-group>
							<view class="f-s-12"><text>我已阅读并同意</text><text class="term" @click="toWeb(11)">《服务条款》</text>
							</view>
						</view>
					</u-form-item>
				</u--form>
				<view class="u-m-t-60">
					<u-button shape="circle" color="#2080F7" text="登 录" :customStyle="{
						width: '260px',
						height: '96rpx',
						fontSize: '32rpx',
						fontWeight: 'bold'
					}" @click="phoneLogin"></u-button>
				</view>
				<view class="u-m-t-40 u-flex u-flex-center" @click="goIndex">
					<u-icon name="home" color="#999" label="游客模式" :size="16" :label-size="14"
						label-color="#999"></u-icon>
				</view>
			</view>
		</view>
	</view>
	<view class="wechat-login">
		<view class="u-light-color f-s-12">- 手机号一键登录并注册 -</view>
		<block v-if="agree.length === 0">
			<button class="phone-login u-m-t-32" @click="noAgree">
				<image src="@/static/imgs/phone-icon.png"></image>
			</button>
		</block>
		<button v-else class="phone-login u-m-t-32" openType="getPhoneNumber" @getphonenumber="authLogin">
			<image src="@/static/imgs/phone-icon.png"></image>
		</button>
	</view>
</template>

<script setup>
	import {
		getToken
	} from '@/utils/auth.js'
	import {
		toast
	} from '@/utils/common';
	import {
		sendPhone
	} from '@/api/login.js'
	import store from '@/store';
	import {
		ref
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	const bottom = uni.getMenuButtonBoundingClientRect().bottom
	const sendMsg = ref('获取验证码')
	const isSend = ref(true)
	const loginForm = ref({
		phone: '',
		code: '',
		loginCode: ''
	})

	const code = ref('') // 用户登录凭证code，有效期5分钟，需要发送到后端服务器进行登录凭证校验，并获取用户信息。
	const agree = ref([])


	onLoad(() => {
		uni.login({
			provider: 'weixin',
			success(suc) {
				code.value = suc.code; // 获取用户登录凭证code，有效期5分钟，需要发送到后端服务器进行登录凭证校验，并获取用户信息。
				loginForm.value.loginCode = suc.code
			}
		})
	})

	// 密码登录
	// const pwdLogin = () => {
	// 	if (agree.value.length == 0) {
	// 		uni.$u.toast('请同意并阅读服务条款')
	// 		return
	// 	}
	// 	store.dispatch('Login', loginForm.value).then(() => {
	// 		loginSuccess()
	// 	})
	// }

	// 手机验证码登录
	const phoneLogin = () => {
		if (agree.value.length == 0) {
			uni.$u.toast('请同意并阅读服务条款')
			return
		}
		if (!loginForm.value.phone) {
			toast("请输入手机号码")
			return
		}
		if (!loginForm.value.code) {
			toast("请输入短信验证码")
			return
		}
		store.dispatch('SmCodeLogin', loginForm.value).then(() => {
			loginSuccess()
		})
	}
	const noAgree = () => {
		toast('请同意并阅读服务条款')
	}
	/**
	 * 手机号授权登录
	 */
	const authLogin = (e) => {
		if (agree.value.length == 0) {
			uni.$u.toast('请同意并阅读服务条款')
			return
		}
		// 允许
		if (e.detail.errMsg == 'getPhoneNumber:ok') {
			console.info(e.detail.code) // 获取用户登录凭证code，有效期5分钟，需要发送到后端服务器进行登录凭证校验，并获取用户信息。
			store.dispatch('AuthLogin', {
				loginCode: code.value,
				phoneCode: e.detail.code
			}).then(() => {
				loginSuccess()
			}).catch((err) => {
				toast("授权登录失败")
			})
			return
		}
		toast("已拒绝授权登录")
	}
	/**
	 * 发送短信验证码
	 */
	function sendPhoneCode() {
		if (!loginForm.value.phone) {
			toast("请输入手机号码")
			return
		}
		sendPhone(loginForm.value.phone).then(res => {
			toast("短信验证码发送成功")
			isSend.value = false
			let time = 60
			sendMsg.value = time + 's'
			let timer = setInterval(() => {
				time--
				sendMsg.value = time + 's'
				if (time == 0) {
					clearInterval(timer)
					isSend.value = true
					sendMsg.value = '发送验证码'
				}
			}, 1000)
		}).catch(err => {
			toast("短信验证码发送失败")
		})
	}

	// 登录成功后，处理函数
	function loginSuccess() {
		const prev = getCurrentPages()[0].route
		// 设置用户信息
		store.dispatch('GetInfo').then(res => {
			toast("登录成功")
			const user = res.user
			if(!user.nickName || !user.avatar ||!user.age ||!user.sex){
				uni.navigateTo({
					url: '/pages/perfectInfo'
				})
				return
			}
			if (prev == 'pages/authLogin') {
				uni.switchTab({
					url: '/pages/mine'
				})
				return
			}
			uni.navigateBack()
		})
	}

	function toWeb(id) {
		uni.navigateTo({
			url: '/subPackages/about/about?id=' + id
		})
	}
	/**
	 * 去首页
	 */
	function goIndex() {
		uni.switchTab({
			url: '/pages/index'
		})
	}
</script>

<style lang="scss" scoped>
	.login {
		height: 100vh;
		width: 100vw;
		background-image: url('https://images.debaoppq.cn/b15c35d207c04562af236a62797b0253.png');
		background-repeat: no-repeat;
		background-size: cover;



		.login-btn {
			padding: 80px 40px;
			text-align: center;
		}

		.bottom-img {
			position: fixed;
			bottom: 0;
			width: 100%;
			height: 280px;
			background-repeat: no-repeat;
			background-size: 100%;
			// background-image: url(https://gm-imgs.wq-info.com/2023/06/08/login-btm_20230608111027A002.png)
		}
	}

	.form-box {
		margin-top: 80px;

		.code_style {
			font-size: 28rpx;
			color: #2080f7;
			margin-right: 10px;
		}

		.term {
			color: #2080f7 !important;
		}
	}

	.wechat-login {
		position: fixed;
		bottom: 60px;
		width: 100%;
		display: flex;
		justify-content: center;
		flex-flow: column;
		align-items: center;

		.u-light-color {
			color: #999;
		}

		.phone-login {
			background-color: transparent !important;
		}

		image {
			width: 50px;
			height: 50px;
		}


	}
</style>